package com.situ.mvc.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mvc.common.ServerResponse;
import com.situ.mvc.entity.Banji;
import com.situ.mvc.entity.PageBean;
import com.situ.mvc.entity.Student;
import com.situ.mvc.service.IBanjiService;
import com.situ.mvc.service.IStudentService;
import com.situ.mvc.service.impl.Banjiserviceimpl;
import com.situ.mvc.service.impl.StudentServiceImpl;
import com.situ.mvc.utill.JDBCUtil;
import com.situ.mvc.utill.JSONUtil;
import com.situ.mvc.utill.ModelConvertUtil;
@Controller
@RequestMapping(value = "/student")

public class StudentController {
	
	@Autowired
	private IStudentService studentService = new StudentServiceImpl();
	@Autowired
	private IBanjiService banjiService = new Banjiserviceimpl();

	@RequestMapping(value = "/xuzekecheng")
	private void xuanzekecheng(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	      String banji = req.getParameter("banjiId");
	      String course = req.getParameter("courseId");
	 
		
		Connection connection11 = null;
		PreparedStatement statement11 = null;
		ResultSet resultSet11 = null;
		try {
			connection11 = JDBCUtil.getConnection();
			String sql11 = "insert into banji_course(banji_id,course_id) values( ?, ?)   ";
			statement11 = connection11.prepareStatement(sql11);
			statement11.setString(1,banji );
			statement11.setString(2, course);
			int count = statement11.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	      
		finally {
			JDBCUtil.close(connection11, statement11, resultSet11);
		}
		ServerResponse serverResponse  = ServerResponse.createSuccess("添加成功");
		JSONUtil.obj2Json(resp, serverResponse);
		
	}

	
	private void suoyoubanjikecheng(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		List<Map<String, Object>> list = null;
		List<Map<String, Object>> list1 = null;
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT name  ,id FROM banji";
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			list = ModelConvertUtil.converToList(resultSet);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, resultSet);
		}
		Connection connection1 = null;
		Statement statement1 = null;
		ResultSet resultSet1 = null;
		try {
			connection1 = JDBCUtil.getConnection();
			String sql = "SELECT name ,id1 FROM course";
			statement1 = connection1.createStatement();
			resultSet1 = statement1.executeQuery(sql);
			list1 = ModelConvertUtil.converToList(resultSet1);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, resultSet);
		}
		req.setAttribute("list", list);
		req.setAttribute("list1", list1);
		// 请求转发到student_list.jsp页面进行展示
		req.getRequestDispatcher("xuanke.jsp").forward(req, resp);
		
	}
	
  	//req.setAttribute("list", list);
	// 请求转发到student_list.jsp页面进行展示
	//req.getRequestDispatcher("/student_banji_list.jsp").forward(req, resp);

	private void banjixuanke(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Map<String, Object>>  list = studentService.banjixuanke();
		
		// 放到一块内存区域里面
		req.setAttribute("list", list);
		// 请求转发到student_list.jsp页面进行展示
		req.getRequestDispatcher("/banji_course.jsp").forward(req, resp);
		
	}
	@RequestMapping(value = "getInsertPage")
	private String getInsertPage(Model model) throws ServletException, IOException {
		//List<Banji> list = banjiService.selectAll();
		List<Banji> list = new ArrayList<Banji>();
		Banji banji1 = new Banji(1, "java1807");
		Banji banji2 = new Banji(2, "java1812");
		list.add(banji1);
		list.add(banji2);
		
		model.addAttribute("list", list);
		//req.getRequestDispatcher("/student_insert.jsp").forward(req, resp);
		return "forward:/student_insert.jsp";
	}
 @RequestMapping(value = "/checkName")
 @ResponseBody
	private ServerResponse checkName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("name");
		boolean isExist = studentService.checkName(name);
		ServerResponse serverResponse =  null;
		if (isExist) {
			serverResponse = serverResponse.createSuccess("该名字已存在");
			
		}else {
			serverResponse = serverResponse.createError("不能存在");
		}
		return serverResponse;
	//	resp.setContentType("text/html;charset=utf-8");
		// {"isExist":isExist}
		//resp.getWriter().write("{\"isExist\":" + isExist + "}");
	}
	@RequestMapping(value = "/pageList" )
	private String pageList(HttpServletRequest req, HttpServletResponse resp,Model model) throws ServletException, IOException {
		// http://localhost:8080/JavaWeb1907/student?method=pageList&pageNo=2&pageSize=3
		String pageNo = req.getParameter("pageNo");
		String pageSize = req.getParameter("pageSize");
		if (null == pageNo || "".equals(pageNo)) {
			pageNo = "1";
		}
		if (null == pageSize || "".equals(pageSize)) {
			pageSize = "8";
		}
		
		PageBean pageBean = studentService.pageList(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
		System.out.println(pageBean);
		
		req.setAttribute("pageBean", pageBean);
	    return"forward:/student_page_list.jsp";
	}
	@RequestMapping(value = "/update",method = RequestMethod.POST)
	@ResponseBody
	private ServerResponse update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("StudentServlet.update()");
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		Student student = new Student(Integer.parseInt(id), name, Integer.parseInt(age), gender);
		boolean isSuccess = studentService.update(student);
		ServerResponse serverResponse = null;
		// 重定向到/JavaWeb1907/student
		if (isSuccess) {
			serverResponse = ServerResponse.createSuccess("修改成功");
		} else {
			serverResponse = ServerResponse.createError("修改失败");
		}
		//resp.sendRedirect(req.getContextPath() + "/student");
		//resp.sendRedirect("/JavaWeb1907/student");
		return serverResponse;
	}
	@RequestMapping(value = "/toUpdate")
	private String toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("StudentServlet.toUpdate()");
		String updateId = req.getParameter("id");
		Student student = studentService.selectById(Integer.parseInt(updateId));
		System.out.println(student);
		
		// 放到一块内存区域里面
		req.setAttribute("student", student);
		
		// 请求转发到student_list.jsp页面进行展示
		//req.getRequestDispatcher("/student_update.jsp").forward(req, resp);	
		return "forward:/student_update.jsp";
	}
@RequestMapping(value = "search")
	private String  search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1、得到前端的数据
		String searchName = req.getParameter("searchName");
		
		// 2、调用Service层方法
		List<Student> list = studentService.search(searchName);
		
		// 3、进行页面的控制
		// 放到一块内存区域里面
		req.setAttribute("list", list);
		// 请求转发到student_list.jsp页面进行展示
	//	req.getRequestDispatcher("/student_list.jsp").forward(req, resp);
		return "forward:/student_list.jsp";
	}
@RequestMapping(value = "insert",method = RequestMethod.POST)
@ResponseBody
	private ServerResponse insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		//String banjiId = req.getParameter("banjiId");
		Student student = new Student(name, Integer.parseInt(age), gender/* , Integer.parseInt(banjiId) */);
		
		boolean isSuccess = studentService.insert(student);
		
		// 重定向到/JavaWeb1907/student
		//resp.sendRedirect(req.getContextPath() + "/student");
		// resp.sendRedirect("/JavaWeb1907/student");
		
		ServerResponse serverResponse = null;
		if (isSuccess) {
			serverResponse = ServerResponse.createSuccess("添加成功");
		} else {
			serverResponse = ServerResponse.createError("添加失败");
		}
		//JSONUtil.obj2Json(resp, serverResponJSse);
		return serverResponse;
	}
	@RequestMapping(value = "/deleteById",method = RequestMethod.POST)
	@ResponseBody
	private ServerResponse deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		
		boolean isSuccess = studentService.deleteById(Integer.parseInt(id));
		
		// 删除完了之后重定向到列表界面再展示所有数据
		// resp.sendRedirect(req.getContextPath() + "/student?method=pageList");
		ServerResponse serverResponse = null;
		if (isSuccess) {
			serverResponse = ServerResponse.createSuccess("删除成功");
		} else {
			serverResponse = ServerResponse.createError("删除失败");
		}
		return serverResponse;
	}

	private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Student>  list = studentService.selectAll();
		
		// 放到一块内存区域里面
		req.setAttribute("list", list);
		// 请求转发到student_list.jsp页面进行展示
		req.getRequestDispatcher("/student_list.jsp").forward(req, resp);
	}
	
	
	private void selectStudentBanjiInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		
		
		List<Map<String, Object>>  list = studentService.selectStudentBanjiInfo();
		
		// 放到一块内存区域里面
		req.setAttribute("list", list);
		// 请求转发到student_list.jsp页面进行展示
		req.getRequestDispatcher("/student_banji_list.jsp").forward(req, resp);
	}
	
	public static void main(String[] args) {
		PageBean pageBean = new PageBean();
		for (int i = 1; i <= pageBean.getTotalPage(); i++) {
			if (pageBean.getPageNo() == i) {
				//<li class="active"><a href="#">3</a></li>
			} else {
				//<li><a href="#">3</a></li>
			}
		}
	}
}
